﻿using System;
using System.Collections.Generic;
using DtoModels;
using Entities;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace Portal.Controllers
{
    /// <summary>
    /// 登录日志 业务逻辑入口
    /// </summary>
    public class LoginInfoController : Controller
    {
        private readonly SqlSugarClient _sqlSugarClient;

        public LoginInfoController(SqlSugarClient sqlSugarClient)
        {
            _sqlSugarClient = sqlSugarClient;
        }

        /// <summary>
        /// 加载登录信息
        /// </summary>
        /// <returns></returns>
        public IActionResult LoadAllLoginInfo(LoginInfoReqDto loginInfoReqDto)
        {

            var totalCount = 0;

            var querySqlQueryable = this._sqlSugarClient.Context.Queryable<sys_loginfo>();

            if (!string.IsNullOrEmpty(loginInfoReqDto.LoginName))
            {
                querySqlQueryable = querySqlQueryable.Where(x => x.loginname == loginInfoReqDto.LoginName);
            }

            if (!string.IsNullOrEmpty(loginInfoReqDto.LoginIp))
            {
                querySqlQueryable = querySqlQueryable.Where(x => x.loginip == loginInfoReqDto.LoginIp);
            }

            if (loginInfoReqDto.StartTime != DateTime.MinValue)
            {
                querySqlQueryable = querySqlQueryable.Where(x => x.logintime >= loginInfoReqDto.StartTime);
            }

            if (loginInfoReqDto.EndTime != DateTime.MinValue)
            {
                querySqlQueryable = querySqlQueryable.Where(x => x.logintime <= loginInfoReqDto.EndTime);
            }

            var queryResult = querySqlQueryable.OrderBy(x => x.id, OrderByType.Desc)
                .ToPageList(loginInfoReqDto.Page, loginInfoReqDto.Limit, ref totalCount);

            var result = new LoginInfoResDto
            {
                Code = 0,
                Msg = "查询成功",
                Count = totalCount,
                Data = queryResult
            };

            return Json(result);
        }

        /// <summary>
        /// 删除登录信息
        /// </summary>
        /// <returns></returns>
        public IActionResult DeleteLoginInfo(int id)
        {
            var result = this._sqlSugarClient.Deleteable<sys_loginfo>().Where(x => x.id == id).ExecuteCommand();

            return Json(result >= 0 ? new { Code = 200, Msg = "删除成功" } : new { Code = 0, Msg = "删除失败" });
        }

        /// <summary>
        /// 批量删除登录信息
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public IActionResult BatchDeleteLoginInfo(List<int> ids)
        {
            var result = this._sqlSugarClient.Deleteable<sys_loginfo>().In(ids).ExecuteCommand();

            return Json(result >= 0 ? new { Code = 200, Msg = "删除成功" } : new { Code = 0, Msg = "删除失败" });
        }
    }
}